<?php

namespace Lite\Utils;

use \Lite\Exception\LiteException;
use \Lite\Utils\StringUtils;

abstract class XmlUtils {

	/**
	 * Lee el archivo y retorna el XML
	 * 
	 * @param string $filePath
	 * @return SimpleXmlElement
	 */
	static function parseFile($filePath){
		$xmlString = FileUtils::readFile($filePath);
		
		if(!self::isXml($xmlString)) {
			throw new LiteException("file does not contains a valid XML");
		}
		
		return self::parseString($xmlString);
	}

	/**
	 * Retorna si <code>$string</code> posee *algo* similar a un XML
	 * 
	 * @param string $string
	 */
	static function isXml($string){
		if(StringUtils::startsWith($string, '<?xml')) {
			return true;
		}
		return StringUtils::matches($string, new RegExp('#<(\w+)>.*</\1>#'));
	}

	/**
	 * Lee el string y retorna el XML que contiene
	 * 
	 * @param $xmlString
	 * @return SimpleXmlElement
	 */
	static function parseString($xmlString){
		
		if(!self::isXml($xmlString)) {
			throw new LiteException("string is not valid XML");
		}
		
		if(StringUtils::contains($xmlString, '<![CDATA[')) {
			
			function parseCDATA($data){
				return htmlentities($data[1]);
			}
			$xmlString = StringUtils::replace($xmlString, "\n", " ");
			$xmlString = StringUtils::replaceWith($xmlString, new RegExp('#<!\[CDATA\[(.*)\]\]>#'), 'parseCDATA');
		}
		
		return simplexml_load_string($xmlString);
	}
}